package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.ExportFormDataVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.MD5Util;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.statistic.help.OssHelper;
import com.xbongbong.pro.statistic.pojo.ExportStatusPojo;
import com.xbongbong.pro.statistic.service.HandleImportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Locale;
import java.util.Objects;

;
/**
 * 导入时一些逻辑处理Service层
 *
 * @author wufeng
 * @date 2018/9/25 10:14
 */
@Service("handleImportService")
public class HandleImportServiceImpl implements HandleImportService {

    private static final Logger LOG = LoggerFactory.getLogger(HandleImportServiceImpl.class);
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private OssHelper ossHelper;

    /**
     * 通过oss异步下载
     *
     * @param formDataListDTO  导出入参
     * @param exportFormDataVO 导出回参
     * @date 2018年5月10日 下午5:25:12
     * @author 梁鲁江
     */
    @Async(value = "exportToOssThreadPool")
    @Override
    public String exportAsync(FormDataListDTO formDataListDTO, ExportFormDataVO exportFormDataVO, String suffix) throws XbbException {
        String[] split = formDataListDTO.getLocale().split("_");
        LocaleContextHolder.setLocale(new Locale(split[0], split[1]));
        String url;
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        String hashKey = corpid + "_" + userId;
        String excelName = "";
        try {
            String name = exportFormDataVO.getName();
            excelName = name;
            name = corpid + "/" + MD5Util.EncoderByMd5(userId) + "/" + name;
            int size = ossHelper.getListWithPrefixSize(name);
            if (size > 0) {
                name = name + "(" + size + ")";
            }
            url = ossHelper.putObjectWorkbook(exportFormDataVO.getWorkbook(), name);

            ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(Objects.toString(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), JSON.toJSONString(new ExportStatusPojo())), ExportStatusPojo.class);
            exportStatusPojo.setFinish(3);
            exportStatusPojo.setUrl(url);
            exportStatusPojo.setName(excelName);
            paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

            PushRefTypePojo.Options options = new PushRefTypePojo.Options();
            options.setDownloadUrl(url);
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userId), Collections.singletonList(0L), 0, null, I18nMessageUtil.getMessage(I18nStringConstant.EXPORT_SUCCESS), excelName, null, options);
            baseProducer.sendMessage(PushTypeEnum.EXPORT_PUSH, messageRabbitMqDTO);
        } catch (Exception e) {
            LOG.error("导出失败", e);
            ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(Objects.toString(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), JSON.toJSONString(new ExportStatusPojo())), ExportStatusPojo.class);
            exportStatusPojo.setFinish(1);
            exportStatusPojo.setErrorMsg(I18nMessageUtil.getMessage(I18nStringConstant.EXPORT_FAILED));
            paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);
            PushRefTypePojo.Options options = new PushRefTypePojo.Options();
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userId), Collections.singletonList(0L), 0, null, I18nMessageUtil.getMessage(I18nStringConstant.EXPORT_FAILED), excelName, null, options);
            baseProducer.sendMessage(PushTypeEnum.EXPORT_PUSH_FAIL, messageRabbitMqDTO);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.OSS_UPLOAD_FAILED);
        }
        return url;
    }

}